$( document ).ready(function() {
    var getTimestampFromDateTime = function(dateTime) {
        var dateStamp = "";
        
        if(dateTime) {
            var date = dateTime.split(" ")[0];
            var time = dateTime.split(" ")[1];

            dateParts = date.split(".");
            timeParts = time.split(":");

            var jsDate = dateParts[1] + "/" + dateParts[0] + "/" + dateParts[2];
            dateStamp = new Date(jsDate).getTime() / 1000;
            dateStamp += (timeParts[0] * 60 * 60) + (timeParts[1] * 60) + (60 * 60 * 3);   
        }

        return dateStamp;
    };
    
    var getDateTimeFromTimestamp = function(timeStamp) {
        if(timeStamp) {
            var dateTime = new Date((timeStamp - (60 * 60 * 3))*1000);

            var month = dateTime.getMonth();
            var day = dateTime.getDate();
            var year = dateTime.getFullYear();

            var hour = dateTime.getHours();
            var minutes = dateTime.getMinutes();

            return (day < 10 ? "0" : "") + day + "." + (month < 10 ? "0" : "") + (month+1) + "." + year + " " + (hour < 10 ? "0" : "") + hour + ":" + (minutes < 10 ? "0" : "") + minutes;
        }  

        return 0;
    };
    
    $('#Search_date').datetimepicker({
        dateFormat: "dd.mm.yy",
        timeFormat: "",
        showTime: false,
        showHour: false,
        showMinute: false,
        onClose: function(dateText, inst) {
            $(this)[0].value = dateText.split(" ")[0];
        },
        onSelect: function(dateText, inst) {
            $(this)[0].value = dateText.split(" ")[0];
        }
    });
    
    $('#Start_time_picker').datetimepicker({
        dateFormat: "dd.mm.yy",
        onClose: function(dateText, inst) {
            var endTimeField = $('#End_time_picker')[0];
            
            if(endTimeField.value.length === 0 && dateText.length > 5) {
                var endTime = getTimestampFromDateTime(dateText);
                endTime += parseInt($('#Movie_duration_mins')[0].value);
                
                endTimeField.value = getDateTimeFromTimestamp(endTime);
                $('#End_timestamp')[0].value = endTime;
            }
            
            $('#Start_timestamp')[0].value = getTimestampFromDateTime(dateText);
        }
    });
    
    $('#End_time_picker').datetimepicker({
        dateFormat: "dd.mm.yy",
        onClose: function(dateText, inst) {
            $('#End_timestamp')[0].value = getTimestampFromDateTime(dateText);
        }
    });
});